#!/bin/bash

cp /Library/OpenSC/lib/opensc-pkcs11.so /usr/local/lib/opensc-pkcs11.so
cp /Library/OpenSC/lib/onepin-opensc-pkcs11.so /usr/local/lib/onepin-opensc-pkcs11.so
if [ -e "/Library/OpenSC/etc/opensc.conf.md5" ]
then
	read cs_fromfile file < "/Library/OpenSC/etc/opensc.conf.md5"
	cs_calculated=$( md5 -q "/Library/OpenSC/etc/opensc.conf")
	if [ "$cs_fromfile" = "$cs_calculated" ]
	then
		mv /Library/OpenSC/etc/opensc.conf.orig /Library/OpenSC/etc/opensc.conf
		md5 -r /Library/OpenSC/etc/opensc.conf  > /Library/OpenSC/etc/opensc.conf.md5
	fi
else
	mv /Library/OpenSC/etc/opensc.conf.orig /Library/OpenSC/etc/opensc.conf
	md5 -r /Library/OpenSC/etc/opensc.conf  > /Library/OpenSC/etc/opensc.conf.md5
fi

for f in \
	/Library/OpenSC/bin/* \
	/Library/OpenSC/etc/bash_completion.d/* \
	/Library/OpenSC/share/doc/opensc \
	/Library/OpenSC/share/man/man1/* \
	/Library/OpenSC/share/man/man5/*
do
	a=/Library/OpenSC
	b=/usr/local
	l="$(dirname ${f/$a/$b})"
	mkdir -p $l
	ln -sf $f $l
done

for f in \
	/Library/LaunchAgents/pkcs11-register.plist \
	/Library/LaunchAgents/opensc-notify.plist
do
	if [ -e "$f" ]
	then
		/bin/launchctl asuser $(id -u "${USER}") /bin/launchctl load "$f" || true
	fi
done

exit 0
